package com.lqm.service.home.impl;

import com.lqm.dao.ProjectScoreDao;
import com.lqm.entity.home.Project;
import com.lqm.entity.home.ProjectScore;
import com.lqm.service.home.ProjectScoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

/**
 * @program: CrowdFunding
 * @description
 * @author: lqm
 * @create: 2018-12-16 16:54
 */

@Service
@Transactional
public class ProjectScoreServiceImpl implements ProjectScoreService {

    @Autowired
    ProjectScoreDao projectScoreDao;

    @Override
    public int saveScore(ProjectScore projectScore) {
        List<ProjectScore> allByHomeUser = projectScoreDao.findAllByHomeUserAndProject(projectScore.getHomeUser(),projectScore.getProject());
        if (allByHomeUser!=null&&allByHomeUser.size()>0){
            return 0;
        }
        projectScoreDao.save(projectScore);
        return 1;
    }

    @Override
    public List<ProjectScore> getAllProjectScoreByProject(Project project) {
        List<ProjectScore> allByProject = projectScoreDao.findAllByProject(project);
        return allByProject;
    }

    @Override
    public Double findAvgByProjectId(Project project) {
        Double avg = projectScoreDao.findAvgByProjectId(project);
        double avg2;
        if (avg!=null){
            avg2= (double)Math.round( avg* 10) / 10;
        }else {
            avg2=0;
        }


        return avg2;
    }

    @Override
    public List<ProjectScore> findAllScoreByProject(Project project, int limit, int page) {
        Sort sort = new Sort(Sort.Direction.DESC, "scoreId");
        Pageable pageable = PageRequest.of(page - 1, limit, sort);
        return projectScoreDao.findAllByProject(project,pageable);
    }
}
